
import path from 'path';
import { app, BrowserWindow, shell, ipcMain, desktopCapturer, screen } from 'electron';
import { autoUpdater } from 'electron-updater';
import axios from 'axios';
const { spawn } = require('child_process');
const os = require('os')
const fs = require('fs')
const Docker = require('dockerode')
import { exec, execFile } from 'child_process';



import MenuBuilder from './menu';
import { resolveHtmlPath } from './util';
import log from 'electron-log';
import baseUrl from '../renderer/src/axios/config';



class AppUpdater {
  constructor() {
    log.transports.file.level = 'info';
    autoUpdater.logger = log;
    autoUpdater.checkForUpdatesAndNotify();
  }
}


//截圖  通过后端和前端   还没有写后台上传功能
ipcMain.on('jietu',(event,arg)=>{

console.log(arg)
const  {width, height } = screen.getPrimaryDisplay().workAreaSize;
desktopCapturer.getSources({types: ['screen'],thumbnailSize:{width,height}})
.then((sources) => {
  const source = sources[0]
const  screeshotpath = path.join(__dirname,`${arg}.png`)
 fs.writeFileSync(screeshotpath, source.thumbnail.toPNG(),(err)=>{
  if(err){
    console.log(err)
    return
  }
console.log(`${screeshotpath}`)


 })
}).catch(err =>{
  console.log(err)
})
})
//开机自动运行

app.setLoginItemSettings({
  openAtLogin: true,
  openAsHidden: true,
})

const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
  // 已经有一个实例在运行，退出当前实例
  app.quit();
} else {
  // 监听第二个实例被运行时
  app.on("second-instance", (event, commandLine, workingDirectory) => {
    // 当有第二个实例被运行时，激活之前的实例并将焦点置于其窗口
    if ( mainWindow) {
      if ( mainWindow.isMinimized())  mainWindow.restore();
      mainWindow.focus();
    }
  });}



let mainWindow: BrowserWindow | null = null;

ipcMain.on('ipc-example', async (event, arg) => {
  const msgTemplate = (pingPong: string) => `IPC test: ${pingPong}`;
  console.log(msgTemplate(arg));
  event.reply('ipc-example', msgTemplate('pong'));
});



//获取容器的中数据
// const docker = new Docker()
// const containerId='pi-consensus'

// const command = 'stellar-core http-command info';

// // 创建 exec 配置
// const execConfig = {
//   Cmd: ['/bin/sh', '-c', command], // 要执行的命令
//   AttachStdout: true, // 将标准输出附加到流中
//   AttachStderr: true // 将标准错误附加到流中
// };

// 创建 exec 实例


// docker.getContainer(containerId).exec(execConfig, (err, exec) => {
//   if (err) {
//     console.error('创建 exec 实例时出错:', err);
//     return;
//   }

//   // 开始执行命令
//   exec.start((err, stream) => {
//     if (err) {
//       console.error('执行命令时出错:', err);
//       return;
//     }
// // console.log(stream)
//     // 监听命令输出
//     // docker.modem.demuxStream(stream, process.stdout, process.stderr);
//     console.log(process.stdout)
//   });
// });


//重启容器
ipcMain.on('docker-restart', async (event, arg) => {
  console.log(arg)

  exec(arg,(error,stedout)=>{
    if(error) {

      event.reply('docker-restart', '运行命令失败');
    }
    if(stedout){
      event.reply('docker-restart', '运行命令成功');
    }
  })

});
//检测c盘下的1.bat文件  并且后台运行运行
ipcMain.on('checknodepi', async (event, arg) => {
  console.log(arg)
  execFile( path.join(__dirname,"../../../","/assets","1.bat" ),(err,setdout)=>{
    if(err){
      event.reply('checknodepi', '运行命令失败');
    }
    if(setdout){
      event.reply('checknodepi', '运行命令成功');
    }
  })
  event.reply('checknodepi', path.join(__dirname,"../../../","/assets","1.bat" ))


// 解决打包之后路径位置变化
// const oldbatpath = path.join(__dirname,"./bat/1.bat");
// const newbatpath = path.join(process.cwd(),'./assets/1.bat')
// fs.stat(oldbatpath, function (err) {
//   if(err){
//     execFile(newbatpath)
//   }else{
//     execFile(oldbatpath)
//   }
// })






});



// 定时获取开机时间
// 从渲染进程哪里获取用户信息

ipcMain.on('userinfo',(event,arg)=>{
  if(!arg){
    console.log("kong")
  }else{
    console.log('userinfo')
    setInterval( async()=>{

      const uptime = os.uptime();
    const days = Math.floor(uptime / (60 * 60 * 24));
    const hours = Math.floor((uptime % (60 * 60 * 24)) / (60 * 60));
    const minutes = Math.floor((uptime % (60 * 60)) / 60);
    const seconds = Math.floor(uptime % 60);
    const uptimedata = `${days}天 ${hours}小时 ${minutes}分钟`
console.log(arg)



    axios
        .get('http://node.dayuan0307.top:300/gf')
        .then(async (resa) => {

       console.log(resa.data)
          await axios
            .get('http://127.0.0.1:31401')
            .then(async (res) => {
              const a = res.data.core_latest_ledger
            // 如果本地区块是1,代表新作，否则  官方减去本地的之 如果相差不到1200 就正常，如果大于1200小于4999代表延迟，如果大于5000 代表延迟厉害
              if (a===1) {


                await axios
                  .post('http://node.dayuan0307.top:300/xiaolu/ed', {
                    name: arg,

                    startup:uptimedata,
                    status: '新作',
                  })
                  .then((res) => {

                  })
              }else{
              const b = resa.data


              const c = b -a

              const c1 = c < 1200
              const c3 = c>1201||c<4999
              const c2 = c > 5000
              if (c3) {


                await axios
                  .post('http://node.dayuan0307.top:300/xiaolu/ed', {
                    name: arg,

                    startup:uptimedata,
                    status: '延迟',
                  })
                  .then((res) => {

                  })
              }


              if (c1) {

                 axios
                  .post('http://node.dayuan0307.top:300/xiaolu/ed', {

                  name: arg,

                  startup:uptimedata,
                    status:'正常'
                  })
                  .then((res) => {

                  })
              }
              if (c2) {

                await axios
                  .post('http://node.dayuan0307.top:300/xiaolu/ed', {
                    name: arg,

                    startup:uptimedata,
                    status: '延迟严重'
                  })
                  .then((res) => {

                  })

              }
            }})
            .catch(async (err) => {

              await axios
                .post('http://node.dayuan0307.top:300/xiaolu/ed', {
                  name: arg,

                  startup:uptimedata,
                  status: '获取本地不正常',

                })
                .then((res) => {
                  console.log("2222")

                })
            })
        })
        .catch((err) => {

        })











    },20000)


  }
//严重延迟  处理方法
  setInterval(async()=>{
  await  axios.get(`http://node.dayuan0307.top:300/xiaolu/query/${arg}`).then(res=>{
      console.log(res.data)
      const data = res.data
      for (let k in data){
        const statusid=data[k].status
        if(statusid==='延迟严重'){
          setInterval(()=>{
            exec('docker restart pi-consensus')
          },7200000)

        }
      }

    })

  },8200000)
  //获取本地区块高度2个小时 没有变化的 处理方法
  setInterval(async()=>{
    await axios.get("http://127.0.0.1:31401").then(res=>{
      console.log(res.data.core_latest_ledger +"老区块")
      const oldlendnumber = res.data.core_latest_ledger
      setInterval(async()=>{
        await axios.get("http://127.0.0.1:31401").then(res=>{
          const newlendnumber = res.data.core_latest_ledger
          console.log(newlendnumber +"新区块")
          if(newlendnumber===1){
            console.log(newlendnumber)
          }else{
          const diffnumber = newlendnumber - oldlendnumber
          console.log(diffnumber)
          if(diffnumber===0){
          axios.post("http://node.dayuan0307.top:300/xiaolu/preboot",{
            name:arg,
            reboot:"是"
          })

          }}
        })

      },3800000)
    })

  },4500000)
})


//严重延迟   ，就重启容器


//获取本地区块高度
ipcMain.on('fetchlend',(event,arg)=>{
  axios.get('http://127.0.0.1:3401').then(async(res)=>{
    console.log(res.data.core_latest_ledger)
    const a = res.data.core_latest_ledger
    await  axios.post('http://node.dayuan0307.top:300/xiaolu/led',{
      name:arg,
      lend:a,
      switc:'0'

    }).then(res=>{
      console.log("tijiaochenggong")
    })

  }).catch(error=>{
    axios.post('http://node.dayuan0307.top:300/xiaolu/led',{
      name:arg,
      lend:'获取本地不正常',
      switc:'0'
    })
  })

})

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support');
  sourceMapSupport.install();
}

const isDebug =
  process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';

if (isDebug) {
  require('electron-debug')();
}

const installExtensions = async () => {
  const installer = require('electron-devtools-installer');
  const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
  const extensions = ['REACT_DEVELOPER_TOOLS'];

  return installer
    .default(
      extensions.map((name) => installer[name]),
      forceDownload,
    )
    .catch(console.log);
};

const createWindow = async () => {
  if (isDebug) {
    await installExtensions();
  }

  const RESOURCES_PATH = app.isPackaged
    ? path.join(process.resourcesPath, 'assets')
    : path.join(__dirname, '../../assets');

  const getAssetPath = (...paths: string[]): string => {
    return path.join(RESOURCES_PATH, ...paths);
  };

  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 228,
    icon: getAssetPath('icon.png'),
    webPreferences: {
      nodeIntegration:true,
      // contextIsolation: false,

      preload: app.isPackaged
        ? path.join(__dirname, 'preload.js')
        : path.join(__dirname, '../../.erb/dll/preload.js'),

    },

  });

  mainWindow.loadURL(resolveHtmlPath('index.html'));

  mainWindow.on('ready-to-show', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();

  // Open urls in the user's browser
  mainWindow.webContents.setWindowOpenHandler((edata) => {
    shell.openExternal(edata.url);
    return { action: 'deny' };
  });

  // Remove this if your app does not use auto updates
  // eslint-disable-next-line
  new AppUpdater();
};

/**
 * Add event listeners...
 */

app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app
  .whenReady()
  .then(() => {
    createWindow();
    app.on('activate', () => {
      // On macOS it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (mainWindow === null) createWindow();
    });
  })
  .catch(console.log);
